package com.youngjun.security;

import com.youngjun.common.controller.support.R;
import com.youngjun.security.service.AuthCallbackService;
import com.youngjun.util.JsonUtils;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Service
public class AuthCallbackServiceImpl implements AuthCallbackService {

    @Override
    public void loginSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        try (PrintWriter printWriter = response.getWriter()) {
            printWriter.print(JsonUtils.getObjectMapper().writeValueAsString(R.create()));
        } catch (Exception ignored) {

        }
    }

    @Override
    public void loginFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) {
//        try {
//            String userId = null;
//            String failMesg = "";
//            String captchaFailMesg = "";
//            if (request.getAttribute("username") != null) {
//                User user = userService.selectByUsername((String) request.getAttribute("username"));
//                if (user != null) {
//                    userId = user.getId();
//                    if (user.getIsAccountNonLocked()) {
//                        Integer fails = user.getFailsCount();
//                        if (fails == null) {
//                            fails = 0;
//                        }
//                        fails++;
//
//                        user.setFailsCount(fails);
//                        // 次数大于10次锁定账户，提示账户登录失败十次，请联系开发人员解锁账户
//                        // 提示错误了几次，还剩余多少次
//                        if (fails >= 10) {
//                            if (user.getLockTime() == null) {
//                                user.setLockTime(new Timestamp(System.currentTimeMillis()));
//                            }
//                            if (user.getIsAccountNonLocked()) {
//                                user.setIsAccountNonLocked(false);
//                            }
//                            failMesg = "账号已被锁定，请联系系统管理员！";
//                        } else {
//                            failMesg = e.getMessage() + "，剩余登录次数" + (10 - fails) + "次";
//                        }
//
//                        userService.updateByPrimaryKey(user);
//                    } else {
//                        failMesg = "账号已被锁定，请联系系统管理员！";
//                    }
//                } else {
//                    userId = (String) request.getAttribute("username");
//                    failMesg = e.getMessage();
//                }
//            }
//            if (e.getCause() != null && "验证码有误".equals(e.getCause().getMessage())) {
//                e = new CustomAuthenticationException("captchaError");
//                captchaFailMesg = "验证码不正确，请重新填写！";
//            }
            try (PrintWriter printWriter = response.getWriter()) {
                printWriter.print(JsonUtils.getObjectMapper().writeValueAsString(R.create().exception(e).data(e.getCause().getMessage())));
            } catch (Exception ignored) {

            }
//            logService.insert(new Log()
//                    .setLogType(Log.LOG_TYPE.USER_LOGIN_FAILED)
//                    .setOperatorUserId(userId)
//                    .setOperatorUserIp(IPUtils.getIpAddress(request))
//                    .setOperatorUserAgent(request.getHeader("user-agent"))
//                    .setUserLoginType(Log.USER_LOGIN_TYPE.PASSWORD)
//            );
    }

    @Override
    public void logoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        try (PrintWriter printWriter = response.getWriter()) {
            printWriter.print(JsonUtils.getObjectMapper().writeValueAsString(R.create()));
//            Object object = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
//            String userId = null;
//            if (object != null) {
//                User user = userService.selectByUsername(String.valueOf(object));
//                if (user != null) {
//                    userId = user.getId();
//                }
//            }
//            logService.insert(new Log()
//                    .setLogType(Log.LOG_TYPE.USER_LOGOUT)
//                    .setOperatorUserId(userId)
//                    .setOperatorUserIp(IPUtils.getIpAddress(request))
//                    .setOperatorUserAgent(request.getHeader("user-agent"))
//                    .setUserLoginType(Log.USER_LOGIN_TYPE.PASSWORD)
//            );
        } catch (Exception ignored) {

        }
    }

    @Override
    public void authEntryPoint(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) {
        try (PrintWriter printWriter = response.getWriter()) {
            printWriter.print(JsonUtils.getObjectMapper().writeValueAsString(R.create().exception(e)));
        } catch (Exception ignored) {

        }
    }

    @Override
    public void accessDenied(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) {
        try (PrintWriter printWriter = response.getWriter()) {
            printWriter.print(JsonUtils.getObjectMapper().writeValueAsString(R.create().exception(e)));
        } catch (Exception ignored) {

        }
    }

}
